layui.use(['layer','form','table','upload'], function() {
    var layer = layui.layer, form = layui.form,table = layui.table,upload = layui.upload,
        fn = {
            data:{
                id:null,
                weightFlag:'0',//按个申报
                includeError:'0',//是否包含错误信息
                importDatas:[],// 导入的原始数据
                noProductNameList:[],// 不存在品名数据
                splitOrderMembers:[],// 分析后的数据
            },
            fullImportDatas:function (data){
                table.render({
                    elem: '#import-datas-list',id:'import-datas-list',limit:30000,page:false,totalRow: true,
                    height:140,text:{none:'暂无数据'},
                    cols:[[
                        {type: 'checkbox',width:35}
                        ,{type:'numbers',title:'序号',width:40,align:'center'}
                        ,{field:'excelRowNo',title:'Excel行',width:60,align:'center'}
                        ,{field:'waybillNo',title:'物流单号',width:140,align: 'edit',templet:'#waybillNoTemp'}
                        ,{field:'goodsName',title:'商品名称',align: 'edit',templet:'#goodsNameTemp'}
                        ,{field:'number',title:'件数',width:80,align: 'edit',totalRow: true,templet:'#numberTemp'}
                        ,{field:'grossWeight',title:'毛重',width:80,align: 'edit',totalRow: true,templet:'#grossWeightTemp'}
                    ]]
                    ,data: data
                });
                var $soif = $('#splitOrderImportForm');
                var $numbers = $soif.find('input[name="number"]');
                var $grossWeights = $soif.find('input[name="grossWeight"]');
                $($numbers[$numbers.length-1]).attr({'LIST':null,disabled:true});
                $($grossWeights[$grossWeights.length-1]).attr({'LIST':null,disabled:true});
                $numbers.bind('blur',function (){
                    var t = 0.0;
                    for(var i=0;i<($numbers.length-1);i++){
                        t += parseFloat($($numbers[i]).val());
                    }
                    $($numbers[$numbers.length-1]).val(Math.round(t*100)/100);
                });
                $grossWeights.bind('blur',function (){
                    var t = 0.0;
                    for(var i=0;i<($grossWeights.length-1);i++){
                        t += parseFloat($($grossWeights[i]).val());
                    }
                    $($grossWeights[$grossWeights.length-1]).val(Math.round(t*100)/100);
                });
                initInput();
            },
            // 填充不存在品名分析
            fullNoProductNameAnalysis:function (){
                table.render({
                    elem: '#no-analysis-list',id:'no-analysis-list',limit:30000,page:false,totalRow: true,
                    height:140,text:{none:'暂无数据'},
                    cols:[[
                        {type: 'checkbox',width:35}
                        ,{type:'numbers',title:'序号',width:40,align:'center'}
                        ,{field:'clearName',title:'品名(替换)'}
                        ,{field:'quantity',title:'同名数量',width:70,align:'center',totalRow: true}
                        ,{field:'improtName',title:'品名(导入)'}
                    ]]
                    ,data: fn.data.noProductNameList
                });
            },
            // 填充分析后数据
            fullAnalysisData:function (){
                table.render({
                    elem: '#split-order-members-list',id:'split-order-members-list',limit:50,limits:[50,100,200,300],page:true,totalRow: false,
                    height:'full-284',text:{none:'暂无数据'},
                    cols:[[
                        {type: 'checkbox',width:35}
                        ,{type:'numbers',title:'序号',width:40,align:'center'}
                        ,{field:'excelRowNo',title:'Excel行',width:60,align:'center'}
                        ,{field:'message',title:'错误消息',width:200}
                        ,{field:'number',title:'件数',width:50,align:'right',totalRow: true}
                        ,{field:'grossWeight',title:'毛重',width:70,align:'right',totalRow: true}
                        ,{field:'totalPrice',title:'总价',width:70,align:'right',totalRow: true}
                        ,{field:'jzNetWeight',title:'单个净重',width:70,align:'right',style:'color:#0ba9f9'}
                        ,{field:'jzUnitPrice',title:'单价(产品库)',width:76,align:'right',style:'color:#0ba9f9'}
                        ,{field:'netWeight',title:'净重',width:70,align:'right',totalRow: true}
                        ,{field:'declaredUnitName',title:'申报单位',width:60,align:'center'}
                        ,{field:'declaredQuantity',title:'申报数量',width:70,align:'right',totalRow: true}
                        ,{field:'unitPrice',title:'单价',width:70,align:'right'}
                        ,{field:'faceNumber',title:'包裹面单号',width:160}
                        ,{field:'declareName',title:'品名(申报)',width:180,templet:'#declareNameTemp'}
                        ,{field:'improtName',title:'品名(导入)',width:180}
                        ,{field:'clearName',title:'品名(清理)',width:180}
                        ,{field:'replaceName',title:'品名(替换)',width:180,templet:'#replaceNameTemp'}
                        ,{field:'goodsName',title:'品名(产品库)',width:180}
                        ,{field:'degree',title:'匹配度',width:90,align:'right',templet:'#degreeTemp'}
                        ,{field:'hsCode',title:'海关编码',width:100,align:'center'}
                        ,{field:'element',title:'申报要素',width:200}
                        ,{field:'unitQuantity',title:'法一数量',width:70,align:'right',totalRow: true}
                        ,{field:'unitName',title:'法一单位',width:60,align:'center'}
                        ,{field:'sunitQuantity',title:'法二数量',width:70,align:'right',totalRow: true}
                        ,{field:'sunitName',title:'法二单位',width:60,align:'center'}
                        ,{field:'customsCurrency',title:'海关币制',width:60,align:'center'}
                        ,{field:'inspectionCurrency',title:'国检币制',width:60,align:'center'}
                        ,{field:'linkMan',title:'收货人名称',width:160}
                        ,{field:'linkAddress',title:'收货人地址',width:200}
                        ,{field:'linkPhone',title:'收货人电话',width:100}
                        ,{field:'destinationCountryName',title:'海关收货人所在国家名称',width:130,align:'center'}
                        ,{field:'inspectionCountryName',title:'国检收货人所在国家名称',width:130,align:'center'}
                        ,{field:'sendLinkMan',title:'发货人名称',width:160}
                        ,{field:'sendLinkAddress',title:'发货人地址',width:200}
                        ,{field:'sendLinkPhone',title:'发货人电话',width:100}
                        ,{field:'sendDestCountryName',title:'海关发货人所在国家名称',width:130,align:'center'}
                        ,{field:'sendInspCountryName',title:'国检发货人所在国家名称',width:130,align:'center'}
                    ]]
                    ,data: fn.data.splitOrderMembers
                });
                formatTableData();
            },
            // 初始化文件上传
            initUpload:function (){
                upload.render({
                    elem: '#importOrder'
                    ,url: '/declare/splitOrder/upload',size:10240
                    ,exts:'xls|xlsx',acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    ,data: {
                        templateCode: function(){
                            return $('#templateCode').val();
                        },
                        weightFlag: function () {
                            return fn.data.weightFlag;
                        }
                    }
                    ,before:function () {
                        show_loading();
                    }
                    ,done: function(res){
                        if(isSuccessWarn(res)){
                            fn.analysisData(res.data);
                        }
                    },error:function () {
                        show_msg('不支持的文件，请按照模板正确填写');
                        hide_loading();
                    }
                })
            },
            // 组装数据
            assemblyData:function () {
                var $splitOrderImportForm = $('#splitOrderImportForm');
                if(!checkedForm($splitOrderImportForm)){return;}
                $splitOrderImportForm.find('input[type="checkbox"]').attr({'checked':null});
                form.render('radio');
                var splitOrderJson = $.extend({},$('#splitOrderForm').serializeJson(),$('#vehicleDeclareForm').serializeJson());
                return {'splitOrder':splitOrderJson,
                    'splitOrderImports':jsonList($splitOrderImportForm.serializeJson()),
                    'splitAgain':fn.data.weightFlag
                };
            },
            // 重新拆分
            splitAgain:function (){
                var params = fn.assemblyData();
                if(!params){return}
                postJSON('/declare/splitOrder/splitAgain',params,function (res){
                    if(isSuccessWarn(res)){
                        fn.analysisData(res.data);
                    }
                });
            },
            // 导出报文
            export:function(){
                var params = fn.assemblyData();
                if(!params){return;}
                if(isEmpty(params.splitOrder.id)){
                    show_msg('请先导出产品进行拆分');return;
                }
                $.post('/declare/splitOrder/export',{'id':params.splitOrder.id},function (res){
                    if(isSuccessWarn(res)){
                        exportFile(res.data);
                    }
                });
            },
            // 导出报文(新)
            exportNew:function(){
                var params = fn.assemblyData();
                if(!params){return;}
                if(isEmpty(params.splitOrder.id)){
                    show_msg('请先导出产品进行拆分');return;
                }
                $.post('/declare/splitOrder/exportNew',{'id':params.splitOrder.id},function (res){
                    if(isSuccessWarn(res)){
                        exportFile(res.data);
                    }
                });
            },
            // 生成订单
            createOrder:function () {
                var params = fn.assemblyData();
                if(!params){return;}
                if(isEmpty(params.splitOrder.id)){
                    show_msg('请先导出产品进行拆分');return;
                }
                postJSON('/declare/splitOrder/createOrder',params,function (res){
                    if(isSuccessWarn(res)){
                        prompt_success('订单生成成功',function () {
                            var mid=parent.parent.obtainMIdByOperation('vehicle_declare_list'),taskArg={"documentId":res.data.id,"documentClass":"","operation":"vehicle_declare_edit"};
                            if(isEmpty(mid)){prompt_warn('对不起您无此权限,请联系贵司管理员授权!');return;}
                            setLocalStorage('TASK_'+mid,JSON.stringify({"docNo":res.data.docNo}));
                            setLocalStorage('AUTO_TASK',JSON.stringify(taskArg));
                            parent.parent.refreshTab(mid);
                        });
                    }
                });
            },
            // 数据解析
            analysisData:function(data){
                // 清空数据
                fn.data.importDatas = [];
                fn.data.noProductNameList = [];
                fn.data.splitOrderMembers = [];
                var priceRatio = 0,packageNum = 0,errorSize = 0;
                if(data){
                    form.val('splitOrderForm',data.splitOrder);
                    form.val('vehicleDeclareForm',data.splitOrder);
                    priceRatio = data.splitOrder.priceRatio;
                    packageNum = data.splitOrder.packageNum;
                    fn.data.id = data.splitOrder.id;
                    fn.data.splitOrderMembers = data.splitOrderMembers;
                    fn.data.importDatas = data.importDatas;
                    // 分析不存在品名
                    var noProductMap = {};
                    $.each(fn.data.splitOrderMembers,function (i,o){
                        if(isEmpty(o.goodsName)){
                            var obj = noProductMap[o.clearName];
                            if(isEmpty(obj)){
                                obj = {clearName:o.clearName,improtName:o.improtName,quantity:0}
                            }
                            obj.quantity = obj.quantity + 1;
                            noProductMap[o.clearName] = obj;
                        }
                    });
                    for(var key in noProductMap){
                        fn.data.noProductNameList.push(noProductMap[key]);
                    }
                    // 错误数
                    $.each(fn.data.splitOrderMembers,function (i,o){
                        if(isNotEmpty(o.message)){
                            errorSize++;
                        }
                    });
                }
                // 价格比例
                $('#priceRatio').html(Math.round(priceRatio*100)+'%');
                // 包裹数
                $('#packageNum').html(packageNum);
                //  错误数
                if(errorSize==0){
                    $('#errorNum').html('错误数：'+errorSize).addClass('success-color').removeClass('color-big-red');
                }else{
                    $('#errorNum').html('错误数：'+errorSize).removeClass('success-color').addClass('color-big-red');
                }
                // 总条数
                $('#totalQty').html(fn.data.splitOrderMembers.length);

                fn.fullAnalysisData();
                fn.fullNoProductNameAnalysis();
                fn.fullImportDatas(fn.data.importDatas);
            },
            // 根据ID获取详情
            obtainDetail:function (id){
                show_loading();
                $.get('/declare/splitOrder/detail',{id:id},function (res){
                    if(isSuccessWarn(res)){
                        fn.analysisData(res.data);
                    }
                });
            },
            // 初始化数据
            init:function (){
                fn.initUpload();
                fn.analysisData();
                var id = getUrlParam('orderId');
                if(isNotEmpty(id)){
                    fn.obtainDetail(id);
                }
            }
        };

    //按千克申报监听
    form.on('checkbox(weightFlag-choice)',function (data) {
        fn.data.weightFlag = this.checked ? "1" : "0";
    });
    form.on('checkbox(error-choice)',function (data) {
        fn.data.includeError = this.checked ? "1" : "0";
    });

    fn.init();
    $('#splitAgain').click(function (){
        fn.splitAgain();
    });
    $('#export').click(function (){
        fn.export();
    });
    $('#exportNew').click(function (){
        fn.exportNew();
    });
    $('#createOrder').click(function (){
        fn.createOrder();
    });
    $(".search-btn").click(function () {
        if(null == fn.data.id) {
            show_error("请先导入原始数据拆单");
            return;
        }
        postJSON('/declare/splitOrder/search',{"id":fn.data.id,"keyword":$("#keyword").val(),"includeError":fn.data.includeError},function (res){
            if(isSuccessWarn(res)){
                fn.analysisData(res.data);
            }
        });
    });
    $("#importDatasDelete").click(function () {
        var data = [],$splitOrderImportForm = $('#splitOrderImportForm')
            ,$ids = $splitOrderImportForm.find('input[name="id"]')
            ,$excelRowNos = $splitOrderImportForm.find('input[name="excelRowNo"]')
            ,$waybillNos = $splitOrderImportForm.find('input[name="waybillNo"]')
            ,$goodsNames = $splitOrderImportForm.find('input[name="goodsName"]')
            ,$numbers = $splitOrderImportForm.find('input[name="number"]')
            ,$grossWeights = $splitOrderImportForm.find('input[name="grossWeight"]');
        if($ids == null || $ids.size() <= 0) {
            show_error("没有可以删除的数据");
            return;
        }
        //必须保留一条数据
        if($ids.size()<=1) {
            show_error("至少需要保留一条数据");
            return;
        }
        //删除后重新渲染数据
        var ids = [];
        var datas = layui.table.checkStatus("import-datas-list").data;
        $.each(datas,function (i,o) {
            ids.push(o.id);
        });
        if(null == ids || ids.length <= 0) {
            show_error("请至少选择一条数据");
            return;
        }
        if(ids.length >= $ids.size() ) {
            show_error("至少需要保留一条数据");
            return;
        }
        //把勾选的移除掉
        for(var i=0;i<$ids.size();i++){
            if(!ids.includes($($ids[i]).val())){
                var item = {
                    id:$($ids[i]).val(),
                    excelRowNo:$($excelRowNos[i]).val(),
                    waybillNo:$($waybillNos[i]).val(),
                    goodsName:$($goodsNames[i]).val(),
                    number:$($numbers[i]).val(),
                    grossWeight:$($grossWeights[i]).val()
                }
                data.push(item);
            }
        }
        fn.fullImportDatas(data);
    });
    $('#vehicleHeadName').autocomplete({
        source: function (request, response) {
            $.post(rurl('declare/vehicleHead/pageList'),{name: trim(request.term),disabled:false},function (res) {
                response($.map(res.data, function (item) {return {label: item.name, value: item.name, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            try{var data = ui.item.data;fullVehicleHeadData(data);}catch (e) {}
        }
    }).focus(function () {
        $(this).select().autocomplete("search");
    }).blur(function () {
        if(isEmpty($(this).val())){
            try{fullVehicleHeadData({id:'',name:''});}catch (e) {}
        }
    });
    $('#trafName').autocomplete({
        source: function (request, response) {
            $.post(rurl('declare/carInfo/list'),{innerCarNum: trim(request.term),disabled:false},function (res) {
                response($.map(res.data, function (item) {return {label: item.innerCarNum, value: item.innerCarNum, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            try{var data = ui.item.data;fullTrafNameData(data);}catch (e) {}
        }
    }).focus(function () {
        $(this).select().autocomplete("search");
    }).blur(function () {
        if(isEmpty($(this).val())){
            try{fullTrafNameData({id:'',innerCarNum:''});}catch (e) {}
        }
    });
});
function degreeClass(degree){
    if(degree==1){
        return 'bg-green';
    }else if(degree<1 && degree >=0.7){
        return 'bg-blue';
    }if(degree<0.7 && degree >=0.5){
        return 'bg-yellow';
    }
    return 'bg-red'
}
function fullCustomerData(data) {
    $('#customerId').val(data.id);
}
function fullVehicleHeadData(data) {
    $('#vehicleHeadId').val(data.id);
}
function fullTrafNameData(data) {
    $('#carInfoId').val(data.id);
}